
package tomkitty;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 *
 * Multithreaded HTTP server class.
 *
 * @author alan, micha
 */
public class TkServer extends Turdlet implements Server, Runnable {

  public Server init(Handler handler, AppContext context) {
    super.init(handler, context);

    (new Thread(this)).start();

    return this;
  }

  public void handle(Request req, Response resp) {
  }

  public void doit() {
  }

  public void run() {
    ServerSocket s = null;
    Configuration config = context.getConfig();
    int port = Integer.valueOf(config.get(CONF_PORT)).intValue();

    Debug.p("starting server on port "+config.get(CONF_PORT));
    try {
      s = new ServerSocket(port);
    } catch(IOException e) {
      System.out.println(e);
      System.exit(1);
    }

    while(true) {
      Socket in = null;

      try {
        in = s.accept();
      } catch(IOException e) {
        System.out.println(e);
        continue;
      }

      try {
        Request req = new TkRequest();
        Response resp = new TkResponse();

        req.setSocket(in);
        resp.setSocket(new TkSocketWrapper(in, resp));

        resp.setStatus(HTTP_OK);

        handler.handle(req, resp);
      } catch (Exception e) {
        // shit out some error codes, or what?
        try {
          in.close();
        } catch (Exception ee) {
          ee.printStackTrace();
        }
      }
    }
  }

  public void serverStart() {
  }

  public void serverStop() {
  }

  public void serverRestart() {
  }

}

